import HashEventListener, { HashEventHandler } from 'listener'
import { screepsApi } from 'utils/request'
import { Shard } from 'utils/screeps'
import './index.less'

const prefix = 'keqing-market'

export default class MarketShow implements HashEventHandler {
    public readonly moduleName = '市场玩家名显示'

    public readonly localStorageKey = 'MarketPlayerShow'

    public matchHash = /^#!\/market\/all\/\w+\/\w+$/

    public enable: boolean

    /**
     * 房间名 => 玩家id
     */
    public roomUserIdMap = new Map<string, string>()
    /**
     * 玩家id => 玩家名
     */
    public userMap = new Map<string, string>()

    public constructor() {
        this.enable = HashEventListener.getModuleEnable(this.localStorageKey)
    }

    /**
     * 显示市场订单玩家名称
     */
    public async onHashChange(hash: string) {
        // 不是市场页面不管
        if (!hash.startsWith('#!/market/all/')) return

        // 解析shard和资源
        const [shard, resource] = hash.split('/').slice(3)
        if (!shard || !resource) return

        // 订单房间名的html元素
        const roomEles = document.querySelectorAll('a._link.ng-star-inserted')

        // 所有订单的房间名
        const roomNames = Array.from(roomEles).map((ele) => ele.innerHTML)

        // 需要查询的房间名
        const queryRooms = roomNames.filter((roomName) => !this.roomUserIdMap.has(roomName))

        const res = await screepsApi.getMapStats(queryRooms, shard as Shard, 'owner0')

        if (!res.ok) {
            console.log('%c查询地图数据失败，请重试', 'color: red;')
            return
        }

        Object.entries(res.stats).forEach(([roomName, stats]) => {
            if (!stats.own?.user) return
            this.roomUserIdMap.set(roomName, stats.own.user)
        })

        Object.entries(res.users).forEach(([userId, user]) => {
            if (!user.username) return
            this.userMap.set(userId, user.username)
        })

        // 显示玩家名
        roomEles.forEach((ele) => {
            const username = this.userMap.get(this.roomUserIdMap.get(ele.innerHTML))
            if (!username) return
            ele.innerHTML = `${ele.innerHTML}(${username})`
        })
    }

    public setEnable(enable: boolean) {
        this.enable = enable
        HashEventListener.setModuleEnable(this.localStorageKey, enable)
    }

    public triggerPanel() {
        const panel = document.createElement('div')
        const title = document.createElement('p')
        const div = document.createElement('div')
        const enableButton = document.createElement('button')
        const disableButton = document.createElement('button')

        title.innerHTML = `是否启用【<strong>${this.moduleName}</strong>】模块？`
        enableButton.innerHTML = '启用'
        disableButton.innerHTML = '禁用'

        panel.setAttribute('class', `${prefix}-panel`)

        enableButton.addEventListener('click', () => {
            this.setEnable(true)
            panel.remove()
        })

        disableButton.addEventListener('click', () => {
            this.setEnable(false)
            panel.remove()
        })

        panel.appendChild(title)
        div.appendChild(enableButton)
        div.appendChild(disableButton)
        panel.appendChild(div)
        document.body.appendChild(panel)
    }
}
